// 云函数入口文件

const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()

const DEFAULT_ROOM_ITEMS = [
  { name: '密码智能锁', exists: true, reportedMissing: false },
  { name: '空调', exists: true, reportedMissing: false },
  { name: '电动窗帘电机集成', exists: true, reportedMissing: false },
  { name: '窗帘', exists: true, reportedMissing: false },
  { name: '伸缩晾衣绳', exists: true, reportedMissing: false },
  { name: '鞋柜', exists: true, reportedMissing: false },
  { name: '投影仪', exists: true, reportedMissing: false },
  { name: '书桌', exists: true, reportedMissing: false },
  { name: '书桌椅', exists: true, reportedMissing: false },
  { name: '灯', exists: true, reportedMissing: false },
  { name: '木凳', exists: true, reportedMissing: false },
  { name: '地板砖每块', exists: true, reportedMissing: false },
  { name: '床头柜', exists: true, reportedMissing: false },
  { name: '床', exists: true, reportedMissing: false },
  { name: '床垫', exists: true, reportedMissing: false },
  { name: '床头软包', exists: true, reportedMissing: false },
  { name: '衣柜', exists: true, reportedMissing: false },
  { name: '浴室玻璃门', exists: true, reportedMissing: false },
  { name: '大神童洗衣机', exists: true, reportedMissing: false },
  { name: '洗漱台和化妆镜', exists: true, reportedMissing: false },
  { name: '热水器', exists: true, reportedMissing: false },
  { name: '九牧花洒', exists: true, reportedMissing: false },
  { name: '浴霸', exists: true, reportedMissing: false },
  { name: '马桶', exists: true, reportedMissing: false },
  { name: '毛巾架和淋浴角架和马桶刷和纸巾盒', exists: true, reportedMissing: false },
  { name: '浴室隔断', exists: true, reportedMissing: false },
  { name: '垃圾桶', exists: true, reportedMissing: false },
  { name: '冰箱', exists: true, reportedMissing: false },
  { name: '水龙头', exists: true, reportedMissing: false },
  { name: '新飞抽油烟机', exists: true, reportedMissing: false },
  { name: '上橱柜', exists: true, reportedMissing: false },
  { name: '下橱柜', exists: true, reportedMissing: false },
  { name: '灶台', exists: true, reportedMissing: false }
]

// 云函数入口函数

exports.main = async (event, context) => {

  const apiType = event.apiType

  const wxContext = cloud.getWXContext()

  let res = {code:0,msg:'',data:null}

  switch(apiType){



    case 'addRoom': {

      // 房间基本信息

      const roomData = {

        _openId: wxContext.OPENID,

        createTime: db.serverDate()

      }

      // 房间号（必填）

      if(event.room){

        roomData.room = event.room

      }

      // 面积

      if(event.area) roomData.area = event.area

      // 户型信息

      if(event.roomType) roomData.roomType = event.roomType // 户型：一室一厅一卫、两室一厅一卫

      // 物业费

      if(event.propertyFee) roomData.propertyFee = event.propertyFee

      // 地址信息（可选）

      if(event.province) roomData.province = event.province

      if(event.city) roomData.city = event.city

      if(event.district) roomData.district = event.district

      if(event.street) roomData.street = event.street

      if(event.address) roomData.address = event.address

      // 房间状态（可选，默认为available）

      if(event.status) roomData.status = event.status

      else roomData.status = 'available'

      // 物品列表（默认初始化）
      if(event.items && Array.isArray(event.items)) roomData.items = event.items
      else roomData.items = DEFAULT_ROOM_ITEMS.map(item => ({ ...item }))

      const addResult = await db.collection('room').add({

        data: roomData

      })

      res = {

        code:200,

        msg:'添加房屋成功',

        data:{

          _id: addResult._id,

          room: roomData.room || ''

        }

      }

      break
    }



    case 'resetRoomItems': {

      const resetRoomId = event.roomId

      if(!resetRoomId){

        res = {

          code:0,

          msg:'房间ID不能为空',

          data:null

        }

        break

      }

      const roomRecord = await db.collection('room').where({

        _id: resetRoomId,

        _openId: wxContext.OPENID

      }).get()

      if(roomRecord.data.length === 0){

        res = {

          code:0,

          msg:'房屋不存在或无权限',

          data:null

        }

        break

      }

      const itemsToSet = DEFAULT_ROOM_ITEMS.map(item => ({ ...item }))

      await db.collection('room').where({

        _id: resetRoomId,

        _openId: wxContext.OPENID

      }).update({

        data: {

          items: itemsToSet,

          updateTime: db.serverDate()

        }

      })

      res = {

        code:200,

        msg:'房间物品已初始化',

        data:{

          roomId: resetRoomId,

          items: itemsToSet

        }

      }

      break
    }



    case 'updateRoom': {

      let roomId = event.roomId

      if(!roomId){

        res = {

          code:0,

          msg:'房屋ID不能为空',

          data:null

        }

        break

      }

      // 先检查房屋是否存在且属于当前用户

      const roomCheck = await db.collection('room').where({

        _id: roomId,

        _openId: wxContext.OPENID

      }).get()

      if(roomCheck.data.length === 0){

        res = {

          code:0,

          msg:'房屋不存在或无权限',

          data:null

        }

        break

      }

      let updateData = {

        updateTime: db.serverDate()

      }

      // 更新房间信息

      if(event.room) updateData.room = event.room

      if(event.area) updateData.area = event.area

      if(event.roomType) updateData.roomType = event.roomType

      if(event.propertyFee) updateData.propertyFee = event.propertyFee

      if(event.province) updateData.province = event.province

      if(event.city) updateData.city = event.city

      if(event.district) updateData.district = event.district

      if(event.street) updateData.street = event.street

      if(event.address) updateData.address = event.address

      // 房间状态

      if(event.status) updateData.status = event.status

      // 物品列表

      if(event.items && Array.isArray(event.items)) updateData.items = event.items

      await db.collection('room').where({

        _id: roomId,

        _openId: wxContext.OPENID

      }).update({

        data: updateData

      })

      res = {

        code:200,

        msg:'更新房屋成功',

        data:{

          roomId: roomId

        }

      }

      break
    }



    case 'getRoomInfo': {

      let getRoomId = event.roomId

      if(!getRoomId){

        res = {

          code:0,

          msg:'房屋ID不能为空',

          data:null

        }

        break

      }

      const room = await db.collection('room').where({

        _id: getRoomId

      }).get()

      if(room.data.length === 0){

        res = {

          code:0,

          msg:'房屋不存在',

          data:null

        }

        break

      }

      res = {

        code:200,

        msg:'获取房屋信息成功',

        data:room.data[0]

      }

      break
    }



    case 'getRoomList': {

      const whereCondition = {

        _openId: wxContext.OPENID

      }

      // 可选的状态筛选

      if(event.status){

        whereCondition.status = event.status

      }

      const roomList = await db.collection('room')

        .where(whereCondition)

        .orderBy('createTime', 'desc')

        .get()

      // 查询每个房间是否有活跃的合同（状态为active）
      let roomIds = roomList.data.map(room => room._id)
      
      let rentedRoomIds = []
      if(roomIds.length > 0){
        const activeContracts = await db.collection('contract')
          .where({
            _openId: wxContext.OPENID,
            roomId: db.command.in(roomIds),
            status: 'active'
          })
          .get()
        
        rentedRoomIds = activeContracts.data.map(contract => contract.roomId)
      }

      // 为每个房间添加isRented字段
      const roomListWithStatus = roomList.data.map(room => ({
        ...room,
        isRented: rentedRoomIds.includes(room._id)
      }))

      res = {

        code:200,

        msg:'获取房屋列表成功',

        data:roomListWithStatus

      }

      break
    }



    case 'getAvailableRoomList': {

      // 查询所有房间
      const allRooms = await db.collection('room')
        .where({
          _openId: wxContext.OPENID
        })
        .orderBy('createTime', 'desc')
        .get()

      // 查询所有活跃合同的房间ID
      let availableRoomIds = allRooms.data.map(room => room._id)
      
      let availableRentedRoomIds = []
      if(availableRoomIds.length > 0){
        const activeContracts = await db.collection('contract')
          .where({
            _openId: wxContext.OPENID,
            roomId: db.command.in(availableRoomIds),
            status: 'active'
          })
          .get()
        
          availableRentedRoomIds = activeContracts.data.map(contract => contract.roomId)
      }

      // 过滤出未租用的房间（isRented为false）
      const availableRooms = allRooms.data
        .filter(room => !availableRentedRoomIds.includes(room._id))
        .map(room => ({
          ...room,
          isRented: false
        }))

      res = {
        code:200,
        msg:'获取可用房间列表成功',
        data:availableRooms
      }

      break
    }



    case 'deleteRoom': {

      let deleteRoomId = event.roomId

      if(!deleteRoomId){

        res = {

          code:0,

          msg:'房屋ID不能为空',

          data:null

        }

        break

      }

      // 先检查房屋是否存在且属于当前用户

      const deleteCheck = await db.collection('room').where({

        _id: deleteRoomId,

        _openId: wxContext.OPENID

      }).get()

      if(deleteCheck.data.length === 0){

        res = {

          code:0,

          msg:'房屋不存在或无权限',

          data:null

        }

        break

      }

      await db.collection('room').where({

        _id: deleteRoomId,

        _openId: wxContext.OPENID

      }).remove()

      res = {

        code:200,

        msg:'删除房屋成功',

        data:{

          roomId: deleteRoomId

        }

      }

      break
    }



    case 'getRoomItems':

      let getItemsRoomId = event.roomId

      if(!getItemsRoomId){

        res = {

          code:0,

          msg:'房间ID不能为空',

          data:null

        }

        break

      }

      // 查询房间信息
      const itemsRoom = await db.collection('room').where({

        _id: getItemsRoomId

      }).get()

      if(itemsRoom.data.length === 0){

        res = {

          code:0,

          msg:'房间不存在',

          data:null

        }

        break

      }

      const roomInfo = itemsRoom.data[0]

      // 返回房间物品列表（如果没有则返回空数组）
      res = {

        code:200,

        msg:'获取房间物品成功',

        data:roomInfo.items || []

      }

    break



    case 'updateRoomItems':

      let updateItemsRoomId = event.roomId

      if(!updateItemsRoomId){

        res = {

          code:0,

          msg:'房间ID不能为空',

          data:null

        }

        break

      }

      // 验证物品数据格式
      if(!event.items || !Array.isArray(event.items)){

        res = {

          code:0,

          msg:'物品数据格式不正确',

          data:null

        }

        break

      }

      // 查询房间信息
      const updateItemsRoom = await db.collection('room').where({

        _id: updateItemsRoomId

      }).get()

      if(updateItemsRoom.data.length === 0){

        res = {

          code:0,

          msg:'房间不存在',

          data:null

        }

        break

      }

      const roomData = updateItemsRoom.data[0]

      // 获取用户信息以验证角色
      const userInfo = await db.collection('user').where({

        _openId: wxContext.OPENID

      }).get()

      if(userInfo.data.length === 0){

        res = {

          code:0,

          msg:'用户不存在',

          data:null

        }

        break

      }

      const user = userInfo.data[0]
      const userRole = user.role || 'landlord'

      // 根据角色处理物品更新
      // 房东可以修改 exists 字段
      // 租客只能修改 reportedMissing 字段
      let updatedItems = event.items.map(item => {

        const existingItem = (roomData.items || []).find(roomItem => roomItem.name === item.name)

        if(userRole === 'landlord'){

          // 房东可以修改所有字段
          return {

            name: item.name,

            exists: item.exists !== undefined ? item.exists : (existingItem ? existingItem.exists : true),

            reportedMissing: item.reportedMissing !== undefined ? item.reportedMissing : (existingItem ? existingItem.reportedMissing : false)

          }

        } else if(userRole === 'tenant'){

          // 租客只能修改 reportedMissing 字段，不能修改 exists
          return {

            name: item.name,

            exists: existingItem ? existingItem.exists : true,

            reportedMissing: item.reportedMissing !== undefined ? item.reportedMissing : (existingItem ? existingItem.reportedMissing : false)

          }

        } else {

          return existingItem || item

        }

      })

      // 更新房间物品
      await db.collection('room').where({

        _id: updateItemsRoomId

      }).update({

        data: {

          items: updatedItems,

          updateTime: db.serverDate()

        }

      })

      res = {

        code:200,

        msg:'更新房间物品成功',

        data:{

          roomId: updateItemsRoomId,

          items: updatedItems

        }

      }

    break



    default:

      res = {

        code:0,

        msg:'没有对应的接口',

        data:null

      }

  }



  return {

    res

  }

}
